/**
 * 49. 字母异位词分组
 * https://leetcode-cn.com/problems/group-anagrams/
 */
const { displayNestedArray } = require('../../libs/public');

const codeA = 'a'.charCodeAt(0);

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
function groupAnagrams(strs) {
  const map = new Map();
  const memory = new Array(26);
  for (let i = 0; i < strs.length; i += 1) {
    memory.fill(0);
    const str = strs[i];
    for (let j = 0; j < str.length; j += 1) {
      const code = str.charCodeAt(j) - codeA;
      memory[code] += 1;
    }
    // eslint-disable-next-line prefer-spread
    const key = String.fromCharCode.apply(String, memory);
    if (map.has(key)) {
      map.get(key).push(str);
    } else {
      map.set(key, [str]);
    }
  }
  const result = new Array(map.size);
  let i = 0;
  // eslint-disable-next-line no-restricted-syntax
  for (const [, value] of map) {
    result[i] = value;
    i += 1;
  }
  return result;
}

console.log(displayNestedArray(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])) === '[[eat,tea,ate],[tan,nat],[bat]]');
console.log(displayNestedArray(groupAnagrams([''])) === '[[]]');
console.log(displayNestedArray(groupAnagrams(['a'])) === '[[a]]');
